// javascript实现一个带并发限制的异步调度器，保证同时运行两个任务

class Scheduler {
  constructor() {
    this.promises = [];
    this.runNum = 0;
  }
  add(promiseCreator) {
    this.promises.push(promiseCreator);
    this.runTast();
    return promiseCreator
  }
  runTast() {
      console.log(this.promises.length)
    /* if (this.runNum < 2) {
      let pro = this.promises.shift();
      console.log(this.promises.length)
      pro.then().then(() => {
        if (this.promises.length > 0) {
          runTast();
        }
      });
      this.runNum++;
      runTast();
    } */
  }
}
const timeout = time =>
  new Promise(resolve => {
    setTimeout(resolve, time);
  });
const scheduler = new Scheduler();
const addTast = (time, order) => {
  scheduler
    .add(() => timeout(time))
    .then(() => {
      console.log(order);
    });
};

addTast(1000, 1);
addTast(400, 2);
addTast(300, 3);
addTast(1200, 4);
// 2314
